Unit 16: Linear Regression: Analytical and Gradient Descent
1. Introduction
This unit introduces Linear Regression,
one of the most fundamental and widely used algorithms in machine learning and statistics.
We will learn how to fit a line (or hyperplane) to data using two complementary approaches:
the analytical closed-form solution (Normal Equation) and the iterative Gradient Descent algorithm.
By the end of this unit, you will understand when to use each method and be able to derive
and implement both from first principles.
Learning Objectives
Formulate Simple and Multiple Linear Regression models in both scalar and matrix notation
Define the Mean Squared Error (MSE) cost function and interpret its geometry
Derive the Normal Equation \( \theta = (X^T X)^{-1} X^T y \) and understand its limitations
Derive Gradient Descent update rules for simple and multiple regression
Implement Gradient Descent step-by-step on small numerical examples
Compare analytical vs. iterative solutions in terms of computational complexity and scalability
2. Theory
2.1 What is Linear Regression?
The goal of linear regression is to model the relationship between one or multiple features
and a continuous target variable. Given data points \( (x_1, y_1), (x_2, y_2), \ldots, (x_m, y_m) \),
we find a line (or hyperplane) that "best fits" the data.
Simple Linear Regression (1 Feature)
\[ \hat{y} = w_1 x + b \]
\( \hat{y} \) (y-hat) = predicted value
\( w \) = weight (slope)
\( b \) = bias (intercept)
\( x \) = input feature
Example: Car Fuel Efficiency
Suppose we want to predict a car's fuel efficiency (miles per gallon) based on how heavy the car is.
A learned model might have:
Bias (intercept) \( b = 34 \) — where the line intersects the y-axis
Weight (slope) \( w = -4.6 \) — heavier cars have lower MPG
Pounds (in 1000s)
Miles per Gallon
3.50
18
3.69
15
3.44
18
3.43
16
4.34
15
4.42
14
2.37
24
2.2 Multiple Linear Regression
A model that predicts gas mileage could additionally use features such as engine displacement (\( x_2 \)),
acceleration (\( x_3 \)), number of cylinders (\( x_4 \)), and horsepower (\( x_5 \)).
The equation becomes:
\[ y = b + w_1 x_1 + w_2 x_2 + w_3 x_3 + w_4 x_4 + w_5 x_5 \]
2.3 Two Approaches for Finding Optimal Parameters
Approach 1: Analytical (Closed-form)
Approach 2: Gradient Descent (Iterative)
Normal Equation — direct calculation using linear algebra
Exact answer in one step
Computationally expensive for large datasets (requires matrix inversion)
No tuning of hyperparameters like learning rate
Iterative optimization — step-by-step improvement
Scales well to large datasets (and even streaming data)
Generalizes to non-linear models, neural networks, logistic regression, etc.
Industry standard for most modern ML
2.4 The Cost Function: Mean Squared Error (MSE)
To measure how "wrong" our predictions are, we use the Mean Squared Error (MSE),
also known as the squared loss. For a model with parameters \( \theta \)
(where \( \theta_0 = b \) is the bias and \( \theta_1, \ldots \) are weights):
The \( \frac{1}{2} \) factor is a convenience that cancels the 2 from differentiation
(you will see this shortly). Minimizing \( \frac{1}{2} \text{MSE} \) is equivalent to
minimizing MSE — the optimal \( \theta \) is the same.
Matrix Notation for Multiple Variables
Let \( X \) be the \( m \times (p+1) \) design matrix (with a column of 1's prepended for the bias),
\( \theta \) the \( (p+1) \times 1 \) parameter vector, and \( y \) the \( m \times 1 \) target vector.
Predictions are \( \hat{y} = X\theta \), and MSE becomes:
Here \( (X\theta - y)^T \) is \( 1 \times m \), \( (X\theta - y) \) is \( m \times 1 \),
and their product is a \( 1 \times 1 \) scalar — exactly like the sum of squared residuals.
2.5 Analytical Solution: The Normal Equation
To find the \( \theta \) that minimizes \( J(\theta) \), we take the derivative with respect
to \( \theta \), set it to zero, and solve algebraically.
\[ \frac{\partial J}{\partial \theta} = \frac{1}{m} \left( X^T X \theta - X^T y \right) = 0 \]
Rearranging gives the Normal Equation:
\[ \theta = \left( X^T X \right)^{-1} X^T y \]
Drawbacks of the Analytical Solution
Drawback
Explanation
Computational Complexity
Matrix inversion is \( O(n^3) \). For \( n = 10{,}000 \) features, ~1 trillion operations!
Non-Invertible Matrix
\( X^T X \) might be singular if features are linearly dependent or \( m \lt p \).
Memory Requirements
Must store the entire dataset in memory; \( X^T X \) is \( (p+1) \times (p+1) \).
No Generalization
Only works for this specific problem — cannot extend to NNs, logistic regression, etc.
2.6 Gradient Descent: The Big Picture
Gradient Descent
is a mathematical technique that iteratively finds the weights and bias that produce
the model with the lowest loss. The model begins with randomized weights and biases
(usually near zero), then repeats the following process:
Calculate the loss \( J(\theta) \) with the current parameters.
Determine the direction to move the parameters that reduces loss
(this is the negative of the gradient vector).
Move the parameter values a small amount in that direction
(scaled by the learning rate \( \alpha \)).
Return to step 1 until the loss plateaus (stops decreasing significantly).
2.7 Gradient Descent for Simple Linear Regression
For the simple model \( h_\theta(x) = \theta_0 + \theta_1 x \), we need the partial
derivatives of \( J \) with respect to both \( \theta_0 \) and \( \theta_1 \).
Initialize: Set \( \theta_0, \theta_1 \) to 0 or small random numbers.
Compute Predictions: For all data points, calculate \( h_\theta(x_i) \).
Compute Gradients: Use the formulas above.
Update Parameters (simultaneously, using the old gradients for BOTH updates).
Loop: Repeat steps 2–4 for many iterations (e.g., 1000) or until \( J \) stops decreasing significantly. Always track \( J \) over iterations to ensure it's minimizing!
2.8 Gradient Descent for Multiple Linear Regression
The multivariate case is a direct extension. With \( h_\theta(x) = \theta^T x = \sum_{j=0}^{p-1} \theta_j x_j \)
(where \( x_0 = 1 \)):
A fitted regression model for house price (in $1000s) on house size (in 100s of sq ft) is:
\( \hat{y} = 50 + 35x \). Click to reveal interpretations.
A. Interpret the intercept \( \theta_0 = 50 \).
A house with zero square footage (not realistic!) is predicted to cost $50,000.
More practically: the intercept anchors the line at $50K when size = 0.
For sizes within the data range, it simply shifts the whole line up/down.
B. Interpret the slope \( \theta_1 = 35 \).
Each additional 100 sq ft of house size is associated with
an average increase of $35,000 in predicted house price.
C. Predict the price of a 1,500 sq ft house. (Watch units! \( x \) is in 100s of sq ft.)
Example 2: Analytical vs. Iterative — Which to Use?
For each scenario, pick the better approach: Normal Equation or Gradient Descent.
Scenario A: 500 training examples, 3 features, need answer quickly for a statistics homework.
Normal Equation. With only 3 features, inversion of a 4×4 matrix is trivial.
You get the exact answer in one line of linear algebra.
Scenario B: 5,000,000 training examples, 500 features, training on GPU with TensorFlow.
Gradient Descent. Inverting a 501×501 matrix is possible,
but GD is far more memory-efficient and scalable. It also generalizes — the same
code template will work for logistic regression and neural networks.
Example 3: Spot the Bug in GD Code Logic
A student writes the following update step. What's wrong?
Simultaneous update violated! The gradient for \( \theta_1 \) must be
computed using the old value of \( \theta_0 \) (from before this iteration began).
The student updated \( \theta_0 \) first, which pollutes the gradient of \( \theta_1 \).
Fix: store both partial derivatives in temporary variables, then apply both updates at once.
4. Numerical Solutions
Problem 1: Single-Step Gradient Descent on Tiny Data
Given one training example \( (x = 2, y = 7) \), current parameters
\( \theta_0 = 1 \), \( \theta_1 = 2 \), and learning rate \( \alpha = 0.1 \).
📘 Step-by-Step Solution
Step 1: Compute the prediction \( \hat{y} = h_\theta(x) \).
Notice that the error was negative (we under-predicted), so both parameters move in the
positive direction, which is the correct "uphill" push to raise predictions closer to \( y = 7 \).
Problem 2: MSE Cost Calculation
Compute \( \frac{1}{2} \text{MSE} \) (i.e., \( J(\theta) \)) for the dataset:
Answers pool: (a) α too small, (b) α well-tuned, (c) α too large / diverging
→ (c) α too large — steps overshoot the minimum and bounce away.
→ (a) α too small — each step is tiny; convergence is glacially slow.
→ (b) α well-tuned — healthy training curve.
6. Interactive Quiz
Your score: 0 / 5
7. Key Takeaways
Linear model form: Simple regression: \( \hat{y} = \theta_0 + \theta_1 x \). Multiple regression: \( \hat{y} = \theta^T x \) (with \( x_0 = 1 \)). Always add the bias column explicitly in matrix code.
MSE cost: \( J(\theta) = \frac{1}{2m} \sum (\hat{y}_i - y_i)^2 \). The \( \frac{1}{2} \) cancels the 2 from differentiation — a standard convention, not a bug.
Normal Equation: \( \theta = (X^T X)^{-1} X^T y \). Exact, one-shot, O(p³). Fails when features are collinear or memory is tight.
Gradient Descent: \( \theta := \theta - \alpha \nabla J \). Works for any differentiable loss (not just MSE). Scales to millions of examples via mini-batches.
Simultaneous updates only: Never interleave gradient computation and parameter updates within one iteration — compute all gradients first, then apply all updates.
Learning rate α is critical: Too small → glacial convergence; too large → divergence / oscillation. Always plot J(θ) vs. iteration to diagnose.
8. Common Pitfalls
Forgetting the bias column (x₀ = 1) in the design matrix. The Normal Equation or matrix-form GD will silently produce wrong results because \( \theta_0 \) has no "feature" to multiply. Always prepend a column of ones.
Using the Normal Equation blindly when XᵀX is singular. Multicollinearity (linearly dependent features) or \( m \lt p \) causes inversion to fail. Fix with feature removal or Ridge regularization, not by "adding a tiny number to the diagonal" ad-hoc.
Updating θ₀ then using the new θ₀ in the gradient of θ₁ within the same iteration. This breaks the simultaneous-update contract and produces incorrect convergence paths. Use temp variables.
Assuming MSE = J(θ) by the numbers. \( J = \frac{1}{2} \text{MSE} \). When a library reports "MSE," multiply by \( \frac{m}{2} \) (or compare trends, not absolute values) to match the in-class formulas.
Feature scaling ignored for Gradient Descent. Without standardization, a feature in the range 0–10,000 will dominate the gradient updates, producing an elongated cost bowl with zig-zagging convergence. We'll formalize this in Unit 17.
Running GD for a fixed number of epochs with no cost monitoring. Always record and plot \( J(\theta) \) during training to detect divergence (α too big) or early plateau (good stop / α too small).